package com.njupt.swg.threadstudyjimin.item04.count;

import com.njupt.swg.threadstudyjimin.annotation.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@NotThreadSafe
public class count1 {
    //总请求数
    public static int clientTotal = 5000;
    //并发数
    public static int threadTotal = 200;
    //计数值
    public static int count = 0;

    public static void main(String[] args) {
        //线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //信号量，控制一次执行多少请求
        Semaphore semaphore = new Semaphore(threadTotal);
        //计数器，到0就表示线程全部执行完
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

        for (int i=0; i<clientTotal; i++){
            executorService.execute(() -> {
                try{
                    semaphore.acquire();
                    add();
                    semaphore.release();
                }catch (Exception e){
                    log.error("semaphore exception",e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("countDownLatch exception",e);
        }
        log.info("result --> {}",count);
        executorService.shutdown();
    }

    public static void add(){
        count++;
    }
}
